import { defineStore } from 'pinia';
import i18n from '@/lang/i18nSetup';
import { getUserInfo } from '@utils/StorageManager';

export const mainStore = defineStore('base', {
    state: () => ({
        pageTitle: 'Kumianmei', // 页面标题
        displayUserId: undefined, // 当前用户ID
        userLanguage: window.sessionStorage.getItem('language') || 'en',
        skeletonLoading: false, // 显示骨架屏
        keepAliveExcludeComponents: [], // KeepAlive忽略的组件
    }),
    getters: {
        GET_TITLE: (state) => state.pageTitle,
        GET_LANG: (state) => state.userLanguage,
        GET_USER_ID: (state) =>
            state.displayUserId || (<{ displayUserId: string }>getUserInfo())?.displayUserId,
        GET_SKELETON_LOADING: (state) => state.skeletonLoading,
    },
    actions: {
        $SET_TITLE(title: string) {
            document.title = title;
            this.pageTitle = title;
        },
        $SET_LANG(lang = 'en') {
            const allowLocales: string[] = ['ar', 'en', 'in', 'tr', 'ur', 'zh', 'ko'];
            const langQuery: boolean = allowLocales.includes(lang.toLowerCase());
            this.userLanguage = langQuery ? lang.toLowerCase() : 'en';
            window.sessionStorage.setItem('language', this.userLanguage.toLowerCase());
            if (i18n) {
                i18n.global.locale.value = this.userLanguage.toLowerCase();
                i18n.global['isRtl'].value = ['ar', 'ur'].includes(this.userLanguage.toLowerCase());
                i18n.global['direction'].value = ['ar', 'ur'].includes(
                    this.userLanguage.toLowerCase()
                )
                    ? 'direction: rtl;'
                    : '';
            }
        },
        $SET_USERID(id) {
            this.displayUserId = id;
        },
        $SET_SKELETON_LOADING(loading = false) {
            this.skeletonLoading = loading;
        },
    },
});
